﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace CommonHelper
{
    public class AppConfigHelper
    {
        /// <summary>
        /// 安全获取AppSetting 获取字符串
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string SGS(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// AppSetting 获取int类型数字
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static int SGI(string key)
        {
            return Convert.ToInt32(ConfigurationManager.AppSettings[key]);
        }

        /// <summary>
        /// AppSetting 获取double类型数字
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static double SGD(string key)
        {
            return Convert.ToDouble(ConfigurationManager.AppSettings[key]);
        }

        /// <summary>
        /// AppSetting 获取bool类型数字
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool SGB(string key)
        {
            return SGS(key) == "true";
        }

        /// <summary>
        /// 添加Config文件的AppSettings节点
        /// </summary>
        /// <param name="configPath">config文件全路径</param>
        /// <param name="keyContent">key的内容</param>
        /// <param name="valueContent">value的内容</param>
        /// <param name="comment">备注</param>
        /// <returns>是否添加成功</returns>
        public static bool AddAppSettingsNode(string configPath, string keyContent, string valueContent, string comment = "")
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                //加载配置文件
                doc.Load(configPath);
                XmlNode recorders = doc.SelectSingleNode("configuration/appSettings");
                if (recorders != null)
                {
                    XmlElement xmlElement = recorders as XmlElement;
                    foreach (XmlNode childNode in xmlElement.ChildNodes)
                    {
                        if (childNode.Name == "add")
                        {
                            string key = childNode.Attributes["key"].Value;
                            if (key == keyContent)
                            {
                                return false;
                            }
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(comment))
                    {
                        var newElementZS = doc.CreateComment(comment);
                        xmlElement.AppendChild(newElementZS);
                    }
                    XmlElement newElement = doc.CreateElement("add");
                    newElement.SetAttribute("key", keyContent);
                    newElement.SetAttribute("value", valueContent);
                    xmlElement.AppendChild(newElement);
                }
                else
                {
                    return false;
                }
                //保存文件
                doc.Save(configPath);
                return true;

            }
            catch (Exception e)
            {
                return false;
            }
        }

        /// <summary>
        /// 设置Config文件的AppSettings节点
        /// </summary>
        /// <param name="configPath">config文件全路径</param>
        /// <param name="keyContent">key的内容</param>
        /// <param name="valueContent">value的内容</param>
        /// <returns>是否添加成功</returns>
        public static bool SetAppSettingsNode(string configPath, string keyContent, string valueContent)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                //加载配置文件
                doc.Load(configPath);
                XmlNode recorders = doc.SelectSingleNode("configuration/appSettings");
                if (recorders != null)
                {
                    XmlElement xmlElement = recorders as XmlElement;
                    foreach (XmlNode childNode in xmlElement.ChildNodes)
                    {
                        if (childNode.Name == "add")
                        {
                            string key = childNode.Attributes["key"].Value;
                            if (key == keyContent)
                            {
                                ((XmlElement)childNode).SetAttribute("value", valueContent);
                                doc.Save(configPath);
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        /// <summary>
        /// 刷新appSettings
        /// </summary>
        public static void RefreshConfig()
        {
            ConfigurationManager.RefreshSection("appSettings");
            //FieldInfo fieldInfo = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
            //if (fieldInfo != null) fieldInfo.SetValue(null, 0);
        }

    }
}
